package com.ba.security.controller;

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.util.SavedRequest;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ba.security.entities.Constants;
import com.ba.security.entities.ResultMethod;
import com.ba.security.entities.User;
import com.ba.security.entities.Role.RoleType;
import com.ba.security.services.UserService;
import com.ba.utils.MathUtil;

@Controller
public class LoginController {
    
    @Autowired
    private UserService userService;
    
    @RequestMapping("login")
    public String login(HttpServletRequest request){
        return "login";
    }
    
    @RequestMapping("login/auth")
    public String doLogin(HttpServletRequest request,HttpServletResponse response){

        String username = request.getParameter("loginname");
        String pwd = request.getParameter("password");
        
        String captcha = request.getParameter("captcha");
        UsernamePasswordToken token = new UsernamePasswordToken(username, pwd, captcha); 
//        UsernamePasswordToken token = new UsernamePasswordToken(username, pwd); 
        Subject currentUser = SecurityUtils.getSubject(); 
        currentUser.login(token); 
        String redirect = request.getContextPath();
        SavedRequest oldRequest = WebUtils.getSavedRequest(request);
        if (oldRequest != null && oldRequest.getRequestURI() != null) {
            redirect = oldRequest.getRequestURI();
        }
        if (redirect.isEmpty()){
            redirect = "/";
        }
        return redirect;
    }
    
    @ResponseBody
    @RequestMapping("admin/index")
    public String index(HttpServletRequest request){
        return "ok";
    }
    
    @ResponseBody
    @RequestMapping("admin/channel")
    public String channel(HttpServletRequest request){
        return "wellcome channel";
    }
    
    @ResponseBody
    @RequestMapping("admin/content")
    public String content(HttpServletRequest request){
        return "wellcome content";
    }
    
    @ResponseBody
    @RequestMapping("admin/sys")
    public String sys(HttpServletRequest request){
        return "wellcome sys";
    }
    
    @RequestMapping("logout")
    public String logout(HttpServletRequest request){
        SecurityUtils.getSubject().logout();  
        return "redirect:/login";
    }
    
    /** 
     * 获取验证码图片和文本(验证码文本会保存在HttpSession中) 
     */  
    @RequestMapping("gen_captcha")
    public void genCaptcha(HttpServletRequest request, HttpServletResponse response) throws IOException {  
        //设置页面不缓存  
        response.setHeader("Pragma", "no-cache");  
        response.setHeader("Cache-Control", "no-cache");  
        response.setDateHeader("Expires", 0);  
        String verifyCode = VerifyCodeUtil.generateTextCode(VerifyCodeUtil.TYPE_NUM_ONLY, 4, null);  
        //将验证码放到HttpSession里面  
        request.getSession().setAttribute(Constants.VALIDATE_CODE, verifyCode);  
        System.out.println("本次生成的验证码为[" + verifyCode + "],已存放到HttpSession中");  
        //设置输出的内容的类型为JPEG图像  
        response.setContentType("image/jpeg");  
        BufferedImage bufferedImage = VerifyCodeUtil.generateImageCode(verifyCode, 90, 30, 5, true, Color.WHITE, null, null);  
        //写给浏览器  
        ImageIO.write(bufferedImage, "JPEG", response.getOutputStream());  
    }  
    
    @RequestMapping(value="/register",method = RequestMethod.GET)
    public String getRegisterPage(HttpServletRequest request){
        return "register";
    }
    
    @RequestMapping(value="/register",method = RequestMethod.POST,produces="application/json;charset=UTF-8")
    public ResultMethod addUser(HttpServletRequest request){
        String username = request.getParameter("loginname");
        String pwd = request.getParameter("password");
//        String roleType = request.getParameter("roleType");
        pwd = MathUtil.getMD5(pwd);
        User user = new User();
        user.setUserName(username);
        user.setPassWord(pwd);
        user.setIsLocked(0);
        user.setRegTime(System.currentTimeMillis());
        ResultMethod resultMethod = new ResultMethod();
        resultMethod.setSucceed(userService.addUser(user,RoleType.USER));  //这里默认提供USER角色，非admin 角色
        return resultMethod;
    }
}
